package com.sf.dlb.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * http工具类
 *
 * Created by jing.tan on 2018/12/10.
 */
public class HttpClientUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	public static String postFromJson(String url, String jsonString) {
		logger.info("postFromJson url{},jsonString{}",url,jsonString);
		CloseableHttpClient httpClient = null;
		StringBuffer sb = new StringBuffer();
		try {
			httpClient = HttpClients.createDefault();
			//设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(30000).setConnectionRequestTimeout(30000)
					.setSocketTimeout(30000).build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);

			StringEntity params = new StringEntity(jsonString, "UTF-8");
			httpPost.addHeader("content-type", "application/json");
			httpPost.setEntity(params);
			httpPost.releaseConnection();
			HttpResponse response = httpClient.execute(httpPost);
			logger.info("postFromJson 返回的状态," + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
			sb = new StringBuffer();
			String line;
			while (null != (line = in.readLine())) {
				sb.append(line).append("\n");
			}
			logger.info("postFromJson 请求返回的json," + sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("postFromJson 请求返回状态异常." + e.getLocalizedMessage());
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}
	/**
	 * header信息需要设置的场合
	 */
	public static String postFromJsonAndHeader(String url, String jsonString, Map<String, String> headers){
		return postFromJsonAndHeader(url,jsonString,headers,30000);
	}
	public static String postFromJsonAndHeader(String url, String jsonString, Map<String, String> headers,int timeOut) {
		logger.info("postFromJsonAndHeader url{},jsonString{},map{}",url,jsonString, GsonUtils.getInstance().toJson(headers));
		CloseableHttpClient httpClient = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httpClient = HttpClients.createDefault();
			//设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut)
					.setSocketTimeout(timeOut).build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			StringEntity params = new StringEntity(jsonString, "UTF-8");
			httpPost.addHeader("content-type", "application/json");
			if(null!=headers){
				for (String key : headers.keySet()) {
					httpPost.addHeader(key, headers.get(key));
				}
			}
			httpPost.setEntity(params);
			httpPost.releaseConnection();
			HttpResponse response = httpClient.execute(httpPost);

			// 打印服务器返回的状态
			logger.info("postFromJsonAndHeader 返回的状态," + response.getStatusLine());

			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
			sb = new StringBuffer();
			String line;
			while (null != (line = in.readLine())) {
				sb.append(line).append("\n");
			}
			logger.info("postFromJsonAndHeader 请求返回的json," + sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("postFromJsonAndHeader 请求返回状态异常." + e.getLocalizedMessage());
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}
	/**
	 * header信息需要设置的场合
	 */
	public static String putFromJsonAndHeader(String url, String jsonString, Map<String, String> headers){
		return putFromJsonAndHeader(url,jsonString,headers,30000);
	}
	public static String putFromJsonAndHeader(String url, String jsonString, Map<String, String> headers,int timeOut) {
		logger.info("putFromJsonAndHeader url{},jsonString{},map{}",url,jsonString, GsonUtils.getInstance().toJson(headers));
		CloseableHttpClient httpClient = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httpClient = HttpClients.createDefault();
			//设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(timeOut).setConnectionRequestTimeout(timeOut)
					.setSocketTimeout(timeOut).build();
			HttpPut httpput = new HttpPut(url);
			httpput.setConfig(requestConfig);
			StringEntity params = new StringEntity(jsonString, "UTF-8");
			httpput.addHeader("content-type", "application/json");
			if(null!=headers){
				for (String key : headers.keySet()) {
					httpput.addHeader(key, headers.get(key));
				}
			}
			httpput.setEntity(params);
			httpput.releaseConnection();
			HttpResponse response = httpClient.execute(httpput);

			// 打印服务器返回的状态
			logger.info("putFromJsonAndHeader 返回的状态," + response.getStatusLine());

			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
			sb = new StringBuffer();
			String line;
			while (null != (line = in.readLine())) {
				sb.append(line).append("\n");
			}
			logger.info("putFromJsonAndHeader 请求返回的json," + sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("putFromJsonAndHeader 请求返回状态异常." + e.getLocalizedMessage());
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}
	/**
	 * postFromData 请求
	 * */
	public static String postFromDataAndHeader(String url, Map<String, String> headers, Map<String,String> fileMap, Map<String,String> parameterMap) {
		logger.info("postFromDataAndHeader url{},headers{},fileMap{},parameterMap{}",url,GsonUtils.getInstance().toJson(headers),GsonUtils.getInstance().toJson(fileMap),GsonUtils.getInstance().toJson(parameterMap));
		CloseableHttpClient httpClient = null;
		StringBuffer sb = new StringBuffer("");
		try {
			httpClient = HttpClients.createDefault();
			//设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(30000).setConnectionRequestTimeout(30000)
					.setSocketTimeout(30000).build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			//请求头
			for (String key : headers.keySet()) {
				httpPost.addHeader(key, headers.get(key));
			}
			//formDate请求体
			// 文件
			Map<String,ContentBody> reqParamMap=new HashMap();
			if(null!=fileMap){
				for (Map.Entry<String,String> file:fileMap.entrySet()) {
					FileBody fileBin = new FileBody(new File(file.getValue()));
					reqParamMap.put(file.getKey(),fileBin);
				}
			}
			// 数据
			if(null!=parameterMap){
				for (Map.Entry<String,String> parameter:parameterMap.entrySet()) {
					String parameterStr=parameterMap.get(parameter.getKey());
					StringBody stringBody=new StringBody(parameterStr,ContentType.TEXT_PLAIN);
					reqParamMap.put(parameter.getKey(),stringBody);
				}
			}

			MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
			for(Map.Entry<String,ContentBody> param : reqParamMap.entrySet()){
				multipartEntityBuilder.addPart(param.getKey(), param.getValue());
			}
			httpPost.setEntity(multipartEntityBuilder.build());
			httpPost.releaseConnection();
			HttpResponse response = httpClient.execute(httpPost);

			logger.info("postFromDataAndHeader 返回的状态," + response.getStatusLine());
			HttpEntity entity = response.getEntity();
			InputStream instream = entity.getContent();
			BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
			sb = new StringBuffer();
			String line;
			while (null != (line = in.readLine())) {
				sb.append(line).append("\n");
			}
			logger.info("postFromDataAndHeader 请求返回的数据，" + sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("postFromDataAndHeader 请求返回状态异常." + e.getLocalizedMessage());
		} finally {
			try {
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}

	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String getRequest(String url) {
		logger.info("getRequest url{}",url);
		String result = null;
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			//设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(30000).setConnectionRequestTimeout(30000)
					.setSocketTimeout(30000).build();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			int code=response.getStatusLine().getStatusCode();
			logger.info("getRequest 响应code "+code);
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
			logger.info("getRequest 响应内容 "+result);
		} catch (Exception e) {
			logger.error("getRequest 处理失败 {}" + e);
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return result;
	}
	/**
	 * get请求
	 * @param url
	 * @return
	 */
	public static String getRequestAndHeader(String url,Map<String, String> headers) {
		logger.info("getRequestAndHeader url{},headers{}",url,GsonUtils.getInstance().toJson(headers));
		String result = null;
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(30000).setConnectionRequestTimeout(30000)
					.setSocketTimeout(30000).build();
			HttpGet httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			//请求头
			for (String key : headers.keySet()) {
				httpGet.addHeader(key, headers.get(key));
			}
			response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			int code=response.getStatusLine().getStatusCode();
			logger.info("getRequestAndHeader getRequest 响应code "+code);
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
			logger.info("getRequestAndHeader getRequest 响应内容 "+result);
		} catch (Exception e) {
			logger.error("getRequestAndHeader 处理失败 {}" + e);
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return result;
	}
	/**
	 * delete请求
	 * @param url
	 * @return
	 */
	public static String deleteRequestAndHeader(String url,Map<String, String> headers) {
		logger.info("deleteRequestAndHeader url{},headers{}",url,GsonUtils.getInstance().toJson(headers));
		String result = null;
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			RequestConfig requestConfig = RequestConfig.custom()
					.setConnectTimeout(30000).setConnectionRequestTimeout(30000)
					.setSocketTimeout(30000).build();
			HttpDelete httpDelete = new HttpDelete(url);
			httpDelete.setConfig(requestConfig);
			//请求头
			for (String key : headers.keySet()) {
				httpDelete.addHeader(key, headers.get(key));
			}
			response = httpclient.execute(httpDelete);
			HttpEntity entity = response.getEntity();
			int code=response.getStatusLine().getStatusCode();
			logger.info("deleteRequestAndHeader getRequest 响应code "+code);
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
			logger.info("deleteRequestAndHeader getRequest 响应内容 "+result);
		} catch (Exception e) {
			logger.error("deleteRequestAndHeader 处理失败 {}" + e);
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return result;
	}

	public static void main(String[] args){

	}
}
